package com.web.common.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * 
 * <dl>
 * <dt>ImageCaptchaServlet</dt>
 * <dd>Description:图形验证码生成器</dd>
 * <dd>Copyright: Copyright (C) 2009</dd>
 * <dd>Company: DM</dd>
 * <dd>CreateDate: 2010-9-16 下午09:57:45</dd>
 * </dl>
 * 
 * @author tangxinjun
 */
public class ImageCaptchaServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 629728177225730367L;
	
	private int height = 0;
	private int width = 0;
	    
	public static final String CAPTCHA_KEY = "captcha_key_name";
	
	 public void init(ServletConfig config) throws ServletException {
		    super.init(config);
		   height=Integer.parseInt(getServletConfig().getInitParameter("height"));
		   width=Integer.parseInt(getServletConfig().getInitParameter("width"));
	 }
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
	    Graphics2D graphics2D = image.createGraphics();
	    graphics2D.setBackground(new Color(54, 155, 215));
	    graphics2D.clearRect(0, 0, width, height);
	    Random r = new Random();
	    String token = Long.toString(Math.abs(r.nextLong()), 36);
	    String ch = token.substring(0,4);
	    GradientPaint gp = new GradientPaint(30, 30, Color.white, 15, 25, Color.white, true);
	    graphics2D.setPaint(gp);
	    Font font=new Font("Verdana", Font.CENTER_BASELINE , 16);
	    graphics2D.setFont(font);
	    graphics2D.drawString(ch, 5, 15);
	    graphics2D.dispose();
	    
	    HttpSession session = request.getSession(true);
	    session.setAttribute(CAPTCHA_KEY, ch);

	    OutputStream outputStream = response.getOutputStream();
	    ImageIO.write(image, "jpeg", outputStream);
	    outputStream.flush();
	    outputStream.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		doGet(request, response);
	}

}
